package main;

import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import domain.User;
import domain.dao.UserDao;


/**
 * last change:  $Date$
 * by:           $Author$
 * revision:     $Revision$
 *
 */
public class ServerConnectionHandler extends IoHandlerAdapter {

  private UserDao userDao;
  
  private Map<Long, User> loggedInUsers;
  
  public ServerConnectionHandler() {
    userDao = new UserDao();
    loggedInUsers = new HashMap<Long, User>();
  }
  
  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    cause.printStackTrace();
  }
  
  public void messageReceived(IoSession session, Object message) throws Exception {
    String parsedMessage = (String)message;
    if(parsedMessage.startsWith("-auth")) {
      String userData[] = parsedMessage.split(":");
      if(userData.length > 2) {
        
//        System.out.println("login : " + userData[1]);
//        System.out.println("pass : " + userData[2]);
        User user = userDao.loadUser(userData[1], userData[2]);
        if(user == null) {
          session.write("-msg:Nieudane logowanie");
          return;
        }
        if(loggedInUsers.containsKey(user.getId())) {
          session.write("-msg:Podany użytkownik jest już zalogowany w systemie");
          session.close(false);
          return;
        }
        user.setIoSession(session);
        session.setAttribute("userId", user.getId());
        loggedInUsers.put(user.getId(), user);
        session.write("-msg:Udane logowanie");
//        System.out.println("user" + user.getLogin() + " " + user.getId());
      }
      return;
    }

//    if(parsedMessage.trim().equalsIgnoreCase("quit")) {
//      session.close(false);
//      return;
//    }
    if(parsedMessage.startsWith("-msg:")) {
      String messageValue = parsedMessage.substring(5);
      if(session.getAttribute("userId") != null) {
        User currentUser = loggedInUsers.get(Long.parseLong(session.getAttribute("userId").toString()));
        String messageForSession = "-msg:" + currentUser.getName() + ": " + messageValue + "\r";
        for (User otherUserInGame : loggedInUsers.values()) {
          if(currentUser.getLocation() == otherUserInGame.getLocation()) {
            otherUserInGame.getIoSession().write(messageForSession);
            //        System.out.println(messageForSession);
          }
        }
        currentUser.getIoSession().write(messageForSession);
      }
    }
  }
  
  public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    System.out.println("IDLE " + session.getIdleCount(status));
  }

  public void sessionClosed(IoSession session) throws Exception {
    if(session.getAttribute("userId") != null) {
      loggedInUsers.remove(Long.parseLong(session.getAttribute("userId").toString()));
    }
  }
  
}
